package recipese.service;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang3.StringEscapeUtils;

import recipese.bean.ShareRecipe;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class EmailService {

	public void sendShareRecipeMessage(ShareRecipe share) {

		final UserService userService = UserServiceFactory.getUserService();
		
		if (userService.isUserLoggedIn()) {
			User user = userService.getCurrentUser();

			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);
			
			String msgBody = "A new recipe has been shared with you on Recipese!\r\n\r\n";
			msgBody += user.getNickname() + " has shared a recipe for " + StringEscapeUtils.escapeHtml4(share.getRecipe().getName()) + " with you.\r\n\r\n";
			msgBody += "http://recipese.appspot.com/mvc/recipes?id=" + share.getRecipeId();

			String htmlBody = "<h2>A new recipe has been shared with you on Recipese!</h2>";
			htmlBody += "<p>" + user.getNickname() + " has shared a recipe for <a href=\"http://recipese.appspot.com/mvc/recipes?id=" + share.getRecipeId() + "\">" + StringEscapeUtils.escapeHtml4(share.getRecipe().getName()) + "</a> with you.</p>";

			try {
				Multipart mp = new MimeMultipart();
				
				MimeBodyPart htmlPart = new MimeBodyPart();
		        htmlPart.setContent(htmlBody, "text/html");
		        mp.addBodyPart(htmlPart);
				
				Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress(user.getEmail(), user.getNickname()));
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(share.getUserId()));
				msg.setSubject("A recipe for " + StringEscapeUtils.escapeHtml4(share.getRecipe().getName()) + " has been shared with you on Recipese!");
				msg.setText(msgBody);
				
				msg.setContent(mp);

				Transport.send(msg);

			} catch (AddressException e) {

			} catch (MessagingException e) {

			} catch (UnsupportedEncodingException e) {

			}
		}
	}

}
